//
//  ViewController.m
//  WestAir
//
//  Created by 张燕枭 on 16/8/29.
//  Copyright © 2016年 张燕枭. All rights reserved.
//

#import "LoginVC.h"
#import "NetworkFactory.h"
#import "SelectDateAndFlightVC.h"
#import "HomeViewController.h"

@interface LoginVC ()<UITextFieldDelegate>{
    
    NSString  *currentUserName;
    NSString  *currentPassWord;
}

@property (weak, nonatomic) IBOutlet UITextField *userName_tf;
@property (weak, nonatomic) IBOutlet UITextField *passWord_tf;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *btnMemory;

@property(nonatomic,strong)NSArray  *arrData;
@property (weak, nonatomic) IBOutlet UILabel *lableVersion;

@end

@implementation LoginVC
@synthesize userName_tf,passWord_tf,loginBtn,arrData;


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self  initDataAndUI];
    

}

-(void)initDataAndUI{

    VIEW_CORNER(userName_tf, buttonCorner21);
    VIEW_CORNER(passWord_tf, buttonCorner21);
    VIEW_CORNER(loginBtn,buttonCorner21);
    
    
    UIButton  *btnUserName=[[UIButton alloc]  initWithFrame:CGRectMake(0, 0, 45, 45)];
    
    [btnUserName setImage:[UIImage imageNamed:@"形状-2.png"] forState:UIControlStateNormal];
    [btnUserName setImageEdgeInsets:UIEdgeInsetsMake(10, 15, 10, 5)];
    userName_tf.leftView=btnUserName;
    userName_tf.rightViewMode=UITextFieldViewModeAlways;
    
    userName_tf.rightView=[[UIButton alloc]  initWithFrame:CGRectMake(0, 0, 45, 45)];
    userName_tf.leftViewMode=UITextFieldViewModeAlways;

    
    UIButton  *btnPassword=[[UIButton alloc]  initWithFrame:CGRectMake(0, 0, 45,45)];
    [btnPassword setImageEdgeInsets:UIEdgeInsetsMake(10, 15, 10, 5)];
     [btnPassword setImage:[UIImage imageNamed:@"形状-3.png"] forState:UIControlStateNormal];
    passWord_tf.leftView=btnPassword;
    passWord_tf.leftViewMode=UITextFieldViewModeAlways;
    passWord_tf.rightViewMode=UITextFieldViewModeAlways;
    passWord_tf.rightView=[[UIButton alloc]  initWithFrame:CGRectMake(0, 0, 45, 45)];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    self.lableVersion.text=[NSString stringWithFormat:@"版本号：v%@",[infoDictionary objectForKey:@"CFBundleShortVersionString"]];


}


-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [[NSNotificationCenter     defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
    // 监听键盘弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAppearanceChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
    

    currentUserName=[[NSUserDefaults  standardUserDefaults]  objectForKey:USER_NAME];
    currentPassWord=[[NSUserDefaults  standardUserDefaults]  objectForKey:PASS_WORD];
    BOOL  isMemory=[[NSUserDefaults  standardUserDefaults]  boolForKey:ISMEMORY];
    if (isMemory) {
        _btnMemory.selected=YES;
        [_btnMemory setImage:[UIImage imageNamed:@"regis_check_btn_selected" ] forState:UIControlStateNormal];
        self.passWord_tf.text=currentPassWord?currentPassWord:@"";
        
        [self  loginStart];
        
    }

    self.userName_tf.text=currentUserName?currentUserName:@"";


}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)keyboardAppearanceChanged:(NSNotification *)note
{
    NSDictionary *userInfo = [note userInfo];
    
    NSValue* beginValue = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
    NSValue* endValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyBoardRectBegin = [beginValue CGRectValue];
    CGRect keyBoardRectEnd = [endValue CGRectValue];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [self moveInputBarWithKeyboardRectFrom:keyBoardRectBegin to:keyBoardRectEnd withDuration:animationDuration];
    
}
-(void)moveInputBarWithKeyboardRectFrom:(CGRect)rectBegin to:(CGRect)rectEnd withDuration:(NSTimeInterval)timeInternal{
    
    [UIView beginAnimations:@"changeAlertView" context:nil];
    
    float keyBoardOriginY   = rectEnd.origin.y;
    if (SCREEN_HEIGHT/2+180>keyBoardOriginY) {
        
        [self.view setOrigin:CGPointMake(0,keyBoardOriginY- (SCREEN_HEIGHT/2+180))];
        [UIView setAnimationDuration:timeInternal+0.5];
    }
    else{
        
        [self.view setOrigin:CGPointMake(0,0)];
        [UIView setAnimationDuration:0];
    }
    [UIView commitAnimations];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma  mark  点击事件

-(void)loginStart{
    
    
    
    // 先判断是否需要版本更新
    
    
    NSMutableDictionary  *dicJsonUpdate=[[NSMutableDictionary  alloc]  init];
    [dicJsonUpdate setObject:[NSNumber numberWithInteger:1] forKey:@"AppType"];
    
    NSData *dataJsonUpdate=[NSJSONSerialization dataWithJSONObject:dicJsonUpdate options:0 error:nil];
    NSString *strJsonUpdate=[[NSString alloc] initWithData:dataJsonUpdate encoding:NSUTF8StringEncoding];
    
    NSDictionary *desStrUpdate=@{@"Jsons": strJsonUpdate};
    
    [[NetworkFactory  alloc]  startPostRequestWithURL:UPDATE andPostValues:desStrUpdate andSuccessBlock:^(NSDictionary *responseJson) {
        
        if ([responseJson[@"IsSuccess"]  integerValue]==1) {
            
            NSString  *url=responseJson[@"Url"];
            NSString   *strVersion=responseJson[@"VersionNo"];
            if (!strVersion.length) {
                [self  gotoLogin];
                
            }
            else{
                strVersion=[strVersion substringFromIndex:1];
                float version= [[strVersion stringByReplacingOccurrencesOfString:@"." withString:@""] floatValue];
                NSString  *strCurrentVersion =buildVersion;
                float currentVersion=[[strCurrentVersion stringByReplacingOccurrencesOfString:@"." withString:@""]  floatValue];
                
                if (version>currentVersion) {
                    CMCCIOTIGAlertControlCustomer *alertControl=  [CMCCIOTTipsCenter  showAlertTitle:@"提示" message:@"有更新内容，立即更新，获得更好体验！" cancelTitle:@"取消" cancelBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
                        
                        self.loginBtn.userInteractionEnabled=NO;
                        [self  performSelector:@selector(gotoLogin) withObject:nil afterDelay:1.0];
                        ;
                    } quireTitle:@"确定" quireBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
                        
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
                        ;
                    }];
                    alertControl.messageAlignment=NSTextAlignmentLeft;
                    [CMCCIOTIGSharePopWindow  sharedWindow].closeType=CMCC_CLOSE_ONLY_BUTTON;
                    ;
                    
                }
                else{
                    [self  gotoLogin];
                }
                
            }
            
        }
        else{
        
        
        }
        
    } andFailBlock:^(NSError *error) {
        
    } ];
    
    
    
}

- (IBAction)login:(UIButton *)sender {
    currentUserName=  [self.userName_tf.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    currentPassWord=[self.passWord_tf.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    [self  loginStart];

}

-(void)gotoLogin{
    
    self.loginBtn.userInteractionEnabled=YES;
    [self  login:currentUserName passWord:currentPassWord];

}

-(void)login:(NSString *)userName  passWord:(NSString  *)
passWord{
    
    NSString  *message=@"请输入账号和密码!";
    
    if (!userName.length) {
        
        [CMCCIOTTipsCenter  showErrorWithStatus:message]  ;
        return;
    }
    
    NSMutableDictionary  *dicJson=[[NSMutableDictionary  alloc]  init];
    [dicJson setObject:userName forKey:@"userAccount"];
    [dicJson setObject:passWord forKey:@"password"];
    
    NSData *dataJson=[NSJSONSerialization dataWithJSONObject:dicJson options:0 error:nil];
    NSString *strJson=[[NSString alloc] initWithData:dataJson encoding:NSUTF8StringEncoding];
    
    NSDictionary *desStr=@{@"Jsons": strJson};
    
    
    [[NetworkFactory  alloc]  startPostRequestWithURL:URL_LOGIN andPostValues:desStr andSuccessBlock:^(NSDictionary *responseJson) {
        
        if ([responseJson[@"IsSuccess"]  integerValue]==1) {
            
            if ([responseJson[@"data"]  isKindOfClass:[NSArray class]]) {
                arrData=responseJson[@"data"];
            }
            else{
                arrData=@[];
                
            }
            
            MemberList  *member=[MemberList  currentUsinfo];
            member.userAccount=userName;
            [CMCCIOTTipsCenter  showSuccessWithStatus:responseJson[@"message"]];
          
            [[NSUserDefaults  standardUserDefaults]  setObject:userName forKey:USER_NAME];
            [[NSUserDefaults  standardUserDefaults]  setObject:passWord  forKey:PASS_WORD];
            if (_btnMemory.selected) {
                [[NSUserDefaults  standardUserDefaults] setBool:YES
                                                         forKey:ISMEMORY];
            }
            else{
            
                [[NSUserDefaults  standardUserDefaults] setBool:NO
                                                         forKey:ISMEMORY];
            }

            [self performSegueWithIdentifier:@"toHomeVC" sender:nil];
            ;
        }
        
    } andFailBlock:^(NSError *error) {
        
    } ];
    
    


}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender NS_AVAILABLE_IOS(5_0){
    
    
    // 整理数据
    
    NSMutableDictionary  *dicMainData=[[NSMutableDictionary  alloc]  init];
    
    [arrData  enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSDictionary  *dicdata=obj;
        NSString *strDate=dicdata[@"FFLIGHTDATE"];
        
        NSArray  *allKeys=[dicMainData  allKeys];
        
        __block  BOOL isHas=NO;
        [allKeys  enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString  *strKey=obj;
            if ([strKey isEqualToString:strDate]) {
                isHas=YES;
                *stop=YES;
            };
        }];
        //      如果存在
        if (isHas) {
            NSMutableArray  *arrhangBan=dicMainData[strDate];
            [arrhangBan  addObject:dicdata[@"FFLIGHTNUMBER"]];
            [dicMainData  setObject:arrhangBan forKey:strDate];
        }
        else{
            
            NSMutableArray  *arrHangBan=[NSMutableArray  new];
            [arrHangBan  addObject:dicdata[@"FFLIGHTNUMBER"]];
            [dicMainData  setObject:arrHangBan forKey:strDate];
        }
        ;
    }];
    

    HomeViewController   *destinAtion=segue.destinationViewController;
    destinAtion.dicMainData=dicMainData;
    

    
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view  endEditing:YES];
}

#pragma mark UITextField Deleget


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];;
    
    return YES;
}

- (IBAction)selectMemory:(id)sender {
    
    _btnMemory.selected=!_btnMemory.selected;
    if (_btnMemory.selected) {
        [_btnMemory setImage:[UIImage imageNamed:@"regis_check_btn_selected"] forState:UIControlStateNormal];
        
    }
    else{
     [_btnMemory setImage:[UIImage imageNamed:@"regis_check_btn"] forState:UIControlStateNormal];
    
    }
    
}

#pragma mark 通知
-(void)textDidChange:(NSNotification *)object{
    
    UITextField  *text= [object  object];
    NSString  *textContent=text.text;
    if (text==userName_tf ) {
        if (textContent.length>30) {
            text.text=[textContent substringToIndex:29];
        }
        
    }
    if (text==passWord_tf ) {
        if (textContent.length>32) {
            text.text=[textContent substringToIndex:31];
        }
        
    }
    
}



@end
